package net.hanjava.roas;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * Client of this class must expicitly close specified stream.
 * 
 * @author behumble@hanjava.net
 * 
 */
public class XlsExportFilter implements BundleExportFilter {
    private OutputStream xlsStream;

    public XlsExportFilter(OutputStream xlsStream) {
        this.xlsStream = xlsStream;
    }

    public void exportBundle(TextBundleModel bundleModel) throws IOException {
        List<Translation> ts = createTranslationsList(bundleModel);

        HSSFWorkbook workbook = new HSSFWorkbook();
        String bundlename = bundleModel.getName();
        HSSFSheet sheet = workbook.createSheet(bundlename);
        // generate header row (contains list of locales)
        HSSFRow hr = sheet.createRow(0); // header row
        for(int ti = 0; ti < ts.size(); ti++) { // translation index
            short colIndex = (short)(ti + 1);
            HSSFCell cell = hr.createCell(colIndex);
            Translation t = ts.get(ti);
            cell.setCellValue(t.getLocale().toString());
        }

        // Key Count is determined by default translation
        Translation dt = ts.get(0); // default translation
        int keyCount = dt.getKeyCount();

        int ri = 1;
        for(Iterator<String> it = dt.getKeyIterator(); it.hasNext();) {
            String key = it.next();
            HSSFRow row = sheet.createRow(ri++);

            // setup key column
            row.createCell((short)0).setCellValue(key);

            for(int ti = 0; ti < ts.size(); ti++) {
                short ci = (short)(ti + 1);
                HSSFCell c = row.createCell(ci);
                Translation t = ts.get(ti);
                String value = t.get(key);
                row.createCell(ci).setCellValue(value);
            }

        }
        workbook.write(xlsStream);
    }

    /**
     * first element must be default locale
     */
    private static List<Translation> createTranslationsList(TextBundleModel model) {
        List<Translation> result = new ArrayList<Translation>();
        Iterator<Translation> it = model.getTranslations();
        Translation dt = model.getDefaultTranslation();
        while(it.hasNext()) {
            Translation t = it.next();
            if(t == dt) { // default
                result.add(0, t);
            } else { // non-default
                result.add(t);
            }
        }
        return result;
    }
}